package com.example.ssd4.domain;

import javafx.collections.ObservableList;

import java.io.*;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class Lesson {
        private String id;
        private String name;
        private String time;
        private String teacher;
        private String score;
        private String credit;
        private String attribute;
        private String capacity;

    public Lesson(String id, String name, String time, String teacher, String score, String credit, String attribute, String capacity) {
        this.id = id;
        this.name = name;
        this.time = time;
        this.teacher = teacher;
        this.score = score;
        this.credit = credit;
        this.attribute = attribute;
        this.capacity = capacity;
    }
    public static List<Lesson> findLessonsByName(List<Lesson> lessons, String str) {
        List<Lesson> matchedLessons = new ArrayList<>();
        String query = str.toLowerCase();

        for (Lesson lesson : lessons) {
            if (lesson.getName().toLowerCase().contains(query)) {
                matchedLessons.add(lesson);
            }
        }

        return matchedLessons;
    }

    public static List<Lesson> findLessonsByTeacher(List<Lesson> lessons, String teacherName) {
        List<Lesson> matchedLessons = new ArrayList<>();
        String query = teacherName.toLowerCase();

        for (Lesson lesson : lessons) {
            if (lesson.getTeacher().toLowerCase().contains(query)) {
                matchedLessons.add(lesson);
            }
        }

        return matchedLessons;
    }

    public static List<Lesson> readFromLogFile(String filePath) {
        List<Lesson> lessons = new ArrayList<>();

        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.trim().replace("Lesson(", "").replace(")", "").split("\", \"");
                if (parts.length == 8) {
                    lessons.add(new Lesson(
                            parts[0].replace("\"", ""),
                            parts[1].replace("\"", ""),
                            parts[2],
                            parts[3],
                            parts[4],
                            parts[5],
                            parts[6],
                            parts[7].replace("\"", "")));
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return lessons;
    }

    public static void main(String[] args) {
        updateLessonScoreStatus("src\\main\\resources\\data\\lesson.log", "390124Z10");
    }
    public static void updateLessonScoreStatus(String filePath, String lessonId){
        try {
            RandomAccessFile file = new RandomAccessFile(filePath, "rw");
            long lastPointer = 0;
            String line;
            while ((line = file.readLine()) != null) {
                String utf8Line = new String(line.getBytes("ISO-8859-1"), "UTF-8");
                if (utf8Line.contains(lessonId)) {
                    String updatedLine = utf8Line.replaceFirst("无记录", "已提交");
                    file.seek(lastPointer);
                    file.write(updatedLine.getBytes("UTF-8"));
                    break;
                }
                lastPointer = file.getFilePointer();
            }
            file.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static List<Lesson> findLessonsByDay(List<Lesson> lessons,String day) {
        List<Lesson> matchedLessons = new ArrayList<>();
        String dayCode = getDayCode(day);

        for (Lesson lesson : lessons) { // 假设 allLessons 是包含所有课程的列表
            if (lesson.getTime().contains(dayCode)) {
                matchedLessons.add(lesson);
            }
        }

        return matchedLessons;
    }

    private static String getDayCode(String weekDay) {
        switch (weekDay) {
            case "周一":
                return "1-";
            case "周二":
                return "2-";
            case "周三":
                return "3-";
            case "周四":
                return "4-";
            case "周五":
                return "5-";
            default:
                return "";
        }
    }

    public static List<Lesson> findLessonsByAttribute(List<Lesson> lessons, String attribute) {
        List<Lesson> matchedLessons = new ArrayList<>();
        for (Lesson lesson : lessons) {
            if (lesson.getAttribute().equalsIgnoreCase(attribute)) {
                matchedLessons.add(lesson);
            }
        }
        return matchedLessons;
    }

    public static List<Lesson> findLessonsByTime(List<Lesson> lessons, String time) {
        List<Lesson> matchedLessons = new ArrayList<>();
        for (Lesson lesson : lessons) {
            if (lesson.getTime().contains(time)) {
                matchedLessons.add(lesson);
            }
        }
        return matchedLessons;
    }

    public static String writeSelectedLessonsToFile(ObservableList<Lesson> lessons, String filePath) {
        StringBuilder msg = new StringBuilder();
        try (OutputStream out = new FileOutputStream(filePath,true);
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out))) { // true 表示追加模式
            for (Lesson lesson : lessons) {
                if (!isLessonExist(filePath, lesson.getId())) {
                    writer.write(lesson.toString());
                    writer.newLine();
                }else {
                    msg.append(lesson.getName() + " ");
                }
            }
            msg.append("已经被选择！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return msg.toString();
    }

    public static void removeSelectedLessons(List<Lesson> allLessons, List<Lesson> toRemove, String filePath) {
        allLessons.removeAll(toRemove);
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (Lesson lesson : allLessons) {
                writer.write(lesson.toString());
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static Set<Integer> parseWeeks(String time) {
        Set<Integer> weeks = new HashSet<>();
        // 假设周数格式是 "1~17"
        String weekRange = time.split(" ")[0];
        String[] rangeParts = weekRange.split("~");
        int startWeek = Integer.parseInt(rangeParts[0]);
        int endWeek = Integer.parseInt(rangeParts[1]);

        for (int i = startWeek; i <= endWeek; i++) {
            weeks.add(i);
        }
        return weeks;
    }

    public static void addLessonToFile(Lesson lesson, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            writer.write(lesson.toString());
            writer.newLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static boolean isTimeConflict(Lesson lesson1, Lesson lesson2) {
        Set<Integer> weeks1 = parseWeeks(lesson1.getTime());
        Set<Integer> weeks2 = parseWeeks(lesson2.getTime());
        boolean weekOverlap = weeks1.stream().anyMatch(weeks2::contains);

        if (!weekOverlap) {
            return false; // 周数完全不重合，没有冲突
        }

        List<String> times1 = parseTimes(lesson1.getTime());
        List<String> times2 = parseTimes(lesson2.getTime());

        for (String time1 : times1) {
            for (String time2 : times2) {
                if (time1.equals(time2)) {
                    return true; // 星期和节次重合，且周数有重叠
                }
            }
        }
        return false; // 无冲突
    }

    private static List<String> parseTimes(String time) {
        List<String> times = new ArrayList<>();
        // 假设时间格式是 "1~17 3-0506,5-0102"
        String[] parts = time.split(" ")[1].split(",");
        for (String part : parts) {
            times.add(part); // 直接添加 "3-0506", "5-0102" 等
        }
        return times;
    }


    public static boolean isLessonExist(String filePath, String id) {
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("Lesson(\"" + id + "\"")) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj == null || getClass() != obj.getClass()) {
            return false;
        }
        Lesson lesson = (Lesson) obj;
        return id != null ? id.equals(lesson.id) : lesson.id == null;
    }

    @Override
    public int hashCode() {
        return id != null ? id.hashCode() : 0;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public String getCapacity() {
        return capacity;
    }

    public void setCapacity(String capacity) {
        this.capacity = capacity;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getTeacher() {
        return teacher;
    }

    public void setTeacher(String teacher) {
        this.teacher = teacher;
    }

    public String getScore() {
        return score;
    }

    public void setScore(String score) {
        this.score = score;
    }

    public String getCredit() {
        return credit;
    }

    public void setCredit(String credit) {
        this.credit = credit;
    }

    public String getAttribute() {
        return attribute;
    }

    public void setAttribute(String attribute) {
        this.attribute = attribute;
    }

    @Override
    public String toString() {
        return String.format("Lesson(\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")",
                id, name, time, teacher, score, credit, attribute, capacity);
    }
}
